package net.oov.identify.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
	
	/**
	 * 在sheet的第一个空行处，写入一行数据
	 * 
	 */
	public static void write(HSSFSheet sheet, Object... obj) {
		int rowNum = sheet.getLastRowNum();
		HSSFRow row = sheet.createRow(rowNum + 1);
		for (int i = 0; i < obj.length; i++) {
			HSSFCell cell = row.createCell((short) i);
			if (obj[i] != null) {
				String classType = obj[i].getClass().getSimpleName();
				if ("String".equals(classType)) {
					cell.setEncoding(HSSFCell.ENCODING_UTF_16);
					cell.setCellValue((String) obj[i]);
				} else if ("Date".equals(classType)) {
					cell.setEncoding(HSSFCell.ENCODING_UTF_16);
					cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format((Date) obj[i]));
				} else if ("Double".equals(classType)
						|| "double".equals(classType)) {
					cell.setCellValue((Double) obj[i]);
				} else if ("Long".equals(classType) || "long".equals(classType)) {
					cell.setCellValue((Long) obj[i]);
				} else {
					cell.setCellValue((Integer) obj[i]);
				}
			}
		}
	}
	
	/**
	 * 生成Excel文件，并写入两列数据
	 * create the excel file, and write two column data
	 * @param file
	 * @param sheetName
	 * @param xName
	 * @param x
	 * @param yName
	 * @param y
	 * @throws IOException
	 */
	public void out2Excel(String file, String sheetName, String xName, int[] x, String yName, int[] y) throws IOException{
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet s = wb.createSheet();
		wb.setSheetName(0, sheetName);
		
		HSSFRow row = null;
		HSSFCell cell = null;
		int firstBlankLine = 0;
		
		//生成表格字段名
		row = s.createRow(firstBlankLine);
		cell = row.createCell((short) 0);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(xName);
		cell = row.createCell((short) 1);
		cell.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell.setCellValue(yName);
		firstBlankLine++;
		
		//加入数据
		for(int i=0;i<x.length;i++){
			row = s.createRow(firstBlankLine+i);
			cell = row.createCell((short) 0);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(x[i]);
			cell = row.createCell((short) 1);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue(y[i]);
		}
		
		FileOutputStream fos = new FileOutputStream(file);
		wb.write(fos);
		fos.close();
	}
	
}
